//
//  MVVMUserInfoController.m
//  CharlesMVX
//
//  Created by Charles on 2020/4/1.
//  Copyright © 2020 Charles. All rights reserved.
//

#import "MVVMUserInfoController.h"

@interface MVVMUserInfoController ()

@property (nonatomic, strong) UserInfoViewModel *viewModel;
@property (nonatomic, strong) MVVMUserInfoView *view;
@property (nonatomic, strong) RACCommand *onClickIconCommand;

@end

@implementation MVVMUserInfoController

+ (instancetype)instanceWithView:(MVVMUserInfoView *)view viewModel:(UserInfoViewModel *)viewModel {
    if (!view || !viewModel)  {
        return nil;
    }
    return [[MVVMUserInfoController alloc]initWithView:view viewModel:viewModel];
}

- (instancetype)initWithView:(MVVMUserInfoView *)view viewModel:(UserInfoViewModel *)viewModel {
    if (self = [super init]) {
        self.view = view;
        self.viewModel = viewModel;
        
        [self bind];
    }
    return self;
}

- (void)bind {
    RAC(self.view.nameLabel,text) = RACObserve(self, viewModel.name);
    RAC(self.view.summaryLabel,text) = RACObserve(self, viewModel.summary);
    RAC(self.view.blogCountLabel,text) = RACObserve(self, viewModel.blogCount);
    RAC(self.view.friendCountLabel,text) = RACObserve(self, viewModel.friendCount);
    
    @weakify(self);
    [RACObserve(self, viewModel.icon) subscribeNext:^(UIImage *icon) {
        @strongify(self);
        [self.view.iconButton setImage:icon forState:UIControlStateNormal];
    }];
    
    [[self.view.iconButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self.onClickIconCommand execute:self.viewModel.user];
    }];
}

- (void)fetchData {
    [[[self.viewModel fetchUserInfoCommand] execute:nil]subscribeError:^(NSError *error) {
       // show error
    }completed:^{
       // do complete
    }];
}

@end
